# -*- coding: utf-8 -*-
#
# Copyright 2016 Ricequant, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


import pytz
from enum import Enum

from .const import EVENT_TYPE


class SimulatorAStockTradingEventSource(object):
    def __init__(self, trading_param):
        self.trading_param = trading_param
        self.timezone = trading_param.timezone
        self.generator = self.create_generator()

    def create_generator(self):
        if self.trading_param.frequency == '1d':
            for date in self.trading_param.trading_calendar:
                yield date.replace(hour=9, minute=0), EVENT_TYPE.DAY_START
                yield date.replace(hour=15, minute=0), EVENT_TYPE.HANDLE_BAR
                yield date.replace(hour=16, minute=0), EVENT_TYPE.DAY_END
        elif self.trading_param.frequency == '1m':
            trades = self.__Minutes_bar()
#             print('---------------'.format(self.trading_param.trading_calendar))
#             for date in self.trading_param.trading_calendar:
            for date in trades:
                if date.hour == 9 and date.minute == 31:
                    yield date, EVENT_TYPE.DAY_START
                elif date.hour == 15 and date.minute == 0:
                    yield date, EVENT_TYPE.DAY_END
                else:
                    yield date, EVENT_TYPE.HANDLE_BAR
    def __Minutes_bar(self):
        import pandas as pd
        minutes = pd.DatetimeIndex([])
        for trade_date in self.trading_param.trading_calendar:
            periord_begin_1 = str(trade_date) + ' 09:31:00';
            periodr_end_1 = str(trade_date) + ' 11:30:00';
            periord_begin_2 = str(trade_date) + ' 13:00:00';
            periodr_end_2 = str(trade_date) + ' 15:00:00';          
            data1 = pd.date_range(periord_begin_1, periodr_end_1, freq='T')
            data2 = pd.date_range(periord_begin_2, periodr_end_2, freq='T')
            minutes = minutes.append(data1)
            minutes = minutes.append(data2)
        return minutes
    def __iter__(self):
        return self

    def __next__(self):
        for date, event in self.generator:
            return date, event

        raise StopIteration

    next = __next__  # Python 2